﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataAccess;
using BastInfos.Areas.Admin.Models;
using DataAccess.Helpers;

namespace BastInfos.Areas.Admin.Controllers
{
	public class ArticleController : ControllerBase
    {
        public ActionResult Index()
        {
            return View(DataRepository.Get<Article>().OrderByDescending(a => a.CreationDate).Take(10));
        }

		[HttpPost]
		public ActionResult Index(FilterModel model)
		{
			PAGE_SIZE = model.Page == "Tout" ? 9999 : Convert.ToInt32(model.Page);
			int total = DataRepository.Get<Article>().Count();
			int page = GetPage(total);

			return View(
				DataRepository.Get<Article>()
					.Where(a => a.id_Category == model.Category || model.Category == -1)
					.Where(a => a.Status == model.Status || model.Status == -1)
					.OrderByDescending(a => a.CreationDate)
					.Skip((page - 1) * PAGE_SIZE)
					.Take(PAGE_SIZE)
			);
		}

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
		[ValidateInput(false)]
		public ActionResult Create(Article model)
        {
            try
			{
				model.CreationDate = DateTime.Now;
				model.EditDate = DateTime.Now;

				DataRepository.Get<Article>().InsertOnSubmit(model);
				DataRepository.Context.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
				return View(model);
            }
        }

        public ActionResult Edit(int id)
		{
			return View(DataRepository.Get<Article>().First(a => a.id_Article == id));
        }

        [HttpPost]
		[ValidateInput(false)]
		public ActionResult Edit(int id, Article model)
        {
            try
			{
				var entity = DataRepository.Get<Article>().First(a => a.id_Article == id);
				entity.id_Category	= model.id_Category;
				entity.DisplayHome	= model.DisplayHome;
				entity.Title		= model.Title;
				entity.Content		= model.Content;
				entity.Introduction	= model.Introduction;
				entity.Status		= model.Status;
				entity.EditDate		= DateTime.Now;
				DataRepository.Context.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
